/**
 * Created by kinfen on 2016/12/15.
 */
const fs = require('fs');
const through = require('through-gulp');
const gutil = require('gulp-util');
const Images = require('images');
var PluginError = gutil.PluginError;

const {fileSize} = require('../file');

const PLUGIN_NAME = "kadm-tinypng";

function gulpPlugin(options) {
    
    var stream = through(function(file, enc, callback) {
        if (file.isNull()) {
            this.push(file); // Do nothing if no contents
            return callback();
        }
        if (file.isBuffer()) {
            var prevLength = file.contents.length;

            var oldimg = Images(file.contents);
            var size = oldimg.size();
            console.log(options);
            console.log(size);
            if ( options.resize.width && size.width > options.resize.width || 
                options.resize.height && size.height > options.resize.height){
                    // console.log('sharp file')
                    sharpImage(file, options.resize, function(err, data) {
                        // console.log(file)
                        // console.log(data)
                        file.contents = data;
                        this.push(file);
                        var img = Images(file.contents);
                        var newsize = img.size();
                        gutil.log(`gulp_tinypng:${gutil.colors.green('✔ ') + file.relative} size:${JSON.stringify(size)} => ${JSON.stringify(newsize)} ${fileSize(prevLength)} => ${fileSize(data.length)}`);
                        return callback();
        
                    }.bind(this));
                } else {
                    this.push(file);
                        gutil.log(`gulp_tinypng:${gutil.colors.green('✔ ') + file.relative} 尺寸符合预期，跳过resize操作 `);
                        return callback();
                }

            
        }
        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, "Stream is not supported");
            return callback();
        }
    });

    // returning the file stream
    return stream;
};

var sharpImage = async function(file, cf, cb){
    var sharp = require('sharp');
    try{
        cb(null, 
            await sharp(file.contents)
            .resize(cf)
            .toBuffer()
        )
    }catch (err){
        cb(err, null);
    }
}
module.exports = gulpPlugin;

